
from rest_framework import serializers
from .models import ProjectModel, ProjectVersionModel
from apps.user.serializers import UserProfileSerializer
from drf_yasg import openapi


class ProjectVersionSerializer(serializers.ModelSerializer):
    """项目版本序列化器"""
    creator = UserProfileSerializer(read_only=True)
    
    class Meta:
        model = ProjectVersionModel
        fields = [
            'id', 'version', 'content', 'created_at', 'creator'
        ]


class FileUploadSerializer(serializers.Serializer):
    """文件上传专用序列化器 - 仅用于接收上传的文件"""
    files = serializers.ListField()
    
    def validate_files(self, files):
        """验证上传的文件"""
        if not files:
            raise serializers.ValidationError("至少需要上传一个文件")
        
        # 检查文件大小限制 (例如每个文件最大50MB)
        max_size = 50 * 1024 * 1024  # 50MB
        for file in files:
            if file.size > max_size:
                raise serializers.ValidationError(f"文件 {file.name} 超过大小限制 (50MB)")
        
        return files
    
    @classmethod
    def schema(self):
        return dict(
            manual_parameters=[
            openapi.Parameter(
                'files',
                openapi.IN_FORM,
                description="上传的文件列表（支持.md/.zip/.jpg/.png等格式）",
                type=openapi.TYPE_ARRAY,
                items=openapi.Items(type=openapi.TYPE_FILE),
                required=True
            )
        ],
        responses={
            200: openapi.Response(
                description="文件上传成功，自动解析完成",
                schema=openapi.Schema(
                    type=openapi.TYPE_OBJECT,
                    properties={
                        'message': openapi.Schema(type=openapi.TYPE_STRING)
                    }
                )
            )
        }
        )


class IndexContentUpdateSerializer(serializers.Serializer):
    """更新index.md内容的序列化器"""
    content = serializers.CharField(
        required=True,
        allow_blank=False,
        help_text="Markdown内容"
    )
    
    def validate_content(self, content):
        """验证内容"""
        if not content.strip():
            raise serializers.ValidationError("内容不能为空")
        
        # 可以添加更多验证，比如内容长度限制
        if len(content) > 100000:  # 100KB限制
            raise serializers.ValidationError("内容过长，请控制在100KB以内")
        
        return content


class VersionRollbackSerializer(serializers.Serializer):
    """版本回滚序列化器"""
    version = serializers.IntegerField(
        required=True,
        min_value=1,
        help_text="要回滚到的版本号"
    )


class VersionCreateSerializer(serializers.Serializer):
    """创建版本序列化器"""
    content = serializers.CharField(
        required=True,
        allow_blank=False,
        help_text="版本内容"
    )


class FilePathSerializer(serializers.Serializer):
    """文件路径序列化器"""
    file_path = serializers.CharField(
        required=True,
        help_text="文件相对路径"
    )
    
    def validate_file_path(self, file_path):
        """验证文件路径"""
        if not file_path or file_path.strip() == "":
            raise serializers.ValidationError("文件路径不能为空")
        
        # 防止路径遍历攻击
        if ".." in file_path or file_path.startswith("/"):
            raise serializers.ValidationError("无效的文件路径")
        
        return file_path


class ProjectSerializer(serializers.ModelSerializer):
    """项目序列化器 - 用于响应数据"""
    creator = UserProfileSerializer(read_only=True)
    versions = ProjectVersionSerializer(many=True, read_only=True)
    
    # 只读字段 - 仅在响应中返回
    project_path = serializers.CharField(read_only=True)
    directory_tree = serializers.SerializerMethodField()
    background_content = serializers.SerializerMethodField()
    index_content = serializers.SerializerMethodField()
    
    class Meta:
        model = ProjectModel
        fields = [
            'id', 'name', 'description', 'creator', 'created_at', 'updated_at',
            'project_path', 'current_content', 'version_count', 'versions',
            'directory_tree', 'background_content', 'index_content'
        ]
        read_only_fields = ['id', 'creator', 'created_at', 'updated_at', 'version_count']
    
    def get_directory_tree(self, obj):
        """获取项目目录树"""
        return obj.get_directory_tree()
    
    def get_background_content(self, obj):
        """获取background.md内容"""
        return obj.get_background_content()
    
    def get_index_content(self, obj):
        """获取index.md内容"""
        return obj.get_index_md_content()
    
    # def create(self, validated_data):
    #     """创建项目 - 仅创建基本记录，文件上传通过专门的接口处理"""
    #     project = ProjectModel.objects.create(**validated_data)
    #     # 🎯 只生成基本的项目目录结构和简单背景
    #     project.update_background_md()
    #     print(f"✅ 创建项目 '{project.name}' (ID: {project.id})，可通过 upload_files 接口上传文件")
    #     return project


class ProjectListSerializer(serializers.ModelSerializer):
    """项目列表序列化器（简化版）"""
    creator = UserProfileSerializer(read_only=True)
    file_count = serializers.SerializerMethodField()
    
    class Meta:
        model = ProjectModel
        fields = [
            'id', 'name', 'description', 'creator', 'created_at', 'updated_at',
            'version_count', 'file_count'
        ]
    
    def get_file_count(self, obj):
        """获取项目文件数量"""
        tree = obj.get_directory_tree()
        return self._count_files(tree)
    
    def _count_files(self, tree):
        """递归计算文件数量"""
        if not tree or tree.get('type') != 'directory':
            return 1 if tree.get('type') == 'file' else 0
        
        count = 0
        for child in tree.get('children', []):
            count += self._count_files(child)
        return count
